export interface MorOption {
  // 组件库配置选项
  baseUrl?: string;
  timeout?: number;
  headers?: Record<string, string>;
  // 与MorghulisOptions兼容的字段
  baseURL?: string;
  minioURL?: string;
  [key: string]: any;
}

export type MorChannels = {
  callbacks: any;
  http: any;
  auth: any;
  [key: string]: any;
};

export type DataItem = { [key: string]: any };
export type DataItemId = string | number;

export type DaoMetaProps = {
  db: string;
  entity: string;
  code?: string;
  auth?: boolean;
};

export type DaoDataProps = {
  includes?: DataItem;
  excludes?: DataItem;
  orders?: any;
};

export type Ticker = {
  length: number | string;
  index: number | string;
  percentage: number;
} | null;

export class Query {
  includes: any;
  excludes: any;
  orders: any;
  page: number;
  size: number;
  code: string;

  constructor(
    includes?: any,
    excludes?: any,
    orders?: any,
    page: number = 1,
    size: number = 10,
    code?: string
  ) {
    this.includes = includes || {};
    this.excludes = excludes || {};
    this.orders = orders || {};
    this.page = page;
    this.size = size;
    this.code = code || 'default';
  }
  
  load(includes?: any, excludes?: any, orders?: any) {
    if (includes) this.includes = includes;
    if (excludes) this.excludes = excludes;
    if (orders) this.orders = orders;
  }
}

export class QueryPayload {
  results: DataItem[] = [];
  total: number = 0;
  
  load(data: any) {
    if (data) {
      this.results = data.results || [];
      this.total = data.total || 0;
    }
  }
}

export class Dao {
  private db: string = '';
  private entity: string = '';
  private callbacks: any = {};
  private http: any = null;

  init(db: string, entity: string, callbacks: any, http: any) {
    this.db = db;
    this.entity = entity;
    this.callbacks = callbacks;
    this.http = http;
  }
  
  meta(code?: string) {
    return this.http.get(`/api/${this.db}/${this.entity}/meta`, {
      params: { code: code || 'default' }
    });
  }
  
  find_many(query: Query) {
    return this.http.get(`/api/${this.db}/${this.entity}`, {
      params: {
        ...query.includes,
        ...query.excludes,
        ...query.orders,
        page: query.page,
        size: query.size,
        code: query.code
      }
    });
  }
  
  save_many(items: DataItem[], callback?: (payload: any) => void) {
    return this.http.post(`/api/${this.db}/${this.entity}/save`, items)
      .then((response: any) => {
        if (callback) {
          callback({
            success: true,
            percentage: 100
          });
        }
        return response;
      });
  }
  
  delete_many(query: Query) {
    return this.http.delete(`/api/${this.db}/${this.entity}`, {
      params: {
        ...query.includes,
        ...query.excludes,
        ...query.orders,
        code: query.code
      }
    });
  }
}